# coding=utf-8
from threading import Thread
from .extensions import mymail
from functools import wraps
from flask import abort
from flask.ext.login import current_user


#: 线程装饰器
def async(f):
    def wrapper(*args, **kwargs):
        thr = Thread(target=f, args=args, kwargs=kwargs)
        thr.start()

    return wrapper


#: 权限控制器
def permission_required(permission):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not current_user.can(permission):
                abort(403)
            return f(*args, **kwargs)

        return decorated_function

    return decorator


#: 管理员权限
def admin_required(f):
    return permission_required(0x80)(f)


#: 多线程发送邮件
@async
def send_async_email(app, msg):
    with app.app_context():
        mymail.send(msg)
